<script lang="ts" setup>
import type { UploadChangeParam } from 'ant-design-vue';

import { computed } from 'vue';

import { MdiAdd, MdiEdit } from '@vben/icons';
import { preferences, usePreferences } from '@vben/preferences';

import {
  Button,
  Checkbox,
  CheckboxGroup,
  Divider,
  Image,
  message,
  Upload,
} from 'ant-design-vue';

import { addImage } from '#/api';
import { accept, headers, upApi } from '#/config/uploadConfig';

interface ImageItem {
  id: number;
  imageUrl: string;
  categoryName: string;
  isRecommend: boolean;
  isRoomTypeCover: boolean;
}
interface ImageList {
  name: string;
  id: number;
  num: number;
  imageList: ImageItem[] | undefined;
}
interface CategoryList {
  id: number;
  name: string;
  num: number;
  categoryTowListResp: { id: number; name: string }[];
}

const props = defineProps({
  currentTabName: {
    type: String,
    default: '全部',
  },
  currentTabId: {
    type: [String, Number],
    default: 'all',
  },
  categoryList: {
    type: Array as () => CategoryList[],
    default: () => [],
  },
  // 图片列表
  list: {
    type: Array as () => ImageList[],
    default: () => [],
  },
  // 选中的id
  selectedImageId: {
    type: Array<number | string>,
    default: () => [],
  },
  // 是否为编辑状态 可选图片
  isEdit: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(['editImage', 'changeCheck', 'upDataList']);

// 默认的二级分类
const twoCategoryId = computed(() => {
  const foundItem = props.categoryList?.find(
    (item: { id: number | string }) => item.id === props.currentTabId,
  );
  return foundItem?.categoryTowListResp[0]?.id || '';
});

// 使用 usePreferences 函数获取主题相关信息
const { isDark } = usePreferences();

// 计算当前主题
const theme = computed(() => {
  if (preferences.theme.mode === 'auto') {
    return isDark.value ? 'dark' : 'light';
  }
  return preferences.theme.mode;
});

// 选择
const changeCheck = (checkedValue: any) => {
  emit('changeCheck', checkedValue);
};

// 编辑图片
const editImage = (image: ImageItem) => {
  emit('editImage', image);
};

// 添加图片
const add = async (src: string, twoId: number | string) => {
  try {
    await addImage({
      imageUrl: src,
      oneCategoryId: props.currentTabId,
      twoCategoryId: twoId,
    });
    await emit('upDataList');
  } catch (error) {
    console.error('添加图片失败', error);
  }
};

const handleChange = async (
  info: UploadChangeParam,
  twoId: number | string,
) => {
  if (info.file.status === 'done') {
    const imgUrl = info.file?.response?.data?.url || '';
    await add(imgUrl, twoId);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name}图片上传失败`);
  }
};
</script>

<template>
  <div>
    <CheckboxGroup
      :value="selectedImageId"
      class="w-full"
      @change="changeCheck"
    >
      <div v-for="(item, index) in list" :key="item.id" class="tab-item w-full">
        <Divider v-if="index !== 0" class="my-5 w-full" />
        <div class="mb-2">
          <p class="text-xl font-medium">
            {{ item.name || '' }} ({{ item.num || 0 }})
          </p>
          <p v-if="item.name === '精选图片'" class="pb-2 text-sm text-gray-700">
            精选图片是酒店最具代表性的一批图片，将会展示在小程序首页轮播图中。
          </p>
        </div>
        <div class="flex flex-wrap">
          <div
            v-for="(img, i) in item.imageList"
            :key="i"
            :class="[theme === 'dark' ? 'bg-gray-700' : 'bg-gray-100']"
            class="image-list relative my-1.5 mr-3 rounded-md"
          >
            <Checkbox
              v-if="isEdit"
              :value="img.id"
              class="absolute left-0 top-0 z-[30] block h-full w-full p-2 pt-1"
            />
            <div
              v-if="img.isRoomTypeCover && currentTabName === '房间'"
              class="bg-primary absolute left-0 top-0 z-[20] rounded-ee-md rounded-ss-md px-3 py-1 text-xs text-white"
            >
              房型首图
            </div>
            <div
              v-else-if="img.isRecommend && currentTabName !== '全部'"
              class="bg-primary absolute left-0 top-0 z-[20] rounded-ee-md rounded-ss-md px-3 py-1 text-xs text-white"
            >
              精选
            </div>
            <div
              class="image-list-img relative cursor-pointer overflow-hidden rounded-t-md"
            >
              <Image
                :preview="!isEdit"
                :src="img.imageUrl"
                class="absolute min-h-full min-w-full rounded-t-md"
              />
              <div
                v-if="!isEdit"
                class="image-edit absolute bottom-0 left-0 z-[10] flex w-full cursor-default items-center justify-center bg-black bg-opacity-70 text-white opacity-0"
              >
                <div class="cursor-pointer p-2" @click="editImage(img)">
                  <MdiEdit class="text-2xl" />
                </div>
              </div>
            </div>
            <div class="image-list-text flex items-center px-2">
              <p class="truncate">
                {{ img.categoryName || item.name }}
              </p>
            </div>
          </div>
          <div
            v-if="!isEdit && currentTabName !== '全部'"
            class="image-list hover:text-primary-500 hover:border-primary-500 relative my-1.5 mr-3 flex cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-gray-400"
          >
            <MdiAdd class="text-2xl" />
            <span class="text-base">点击上传</span>
            <Upload
              :accept="accept"
              :action="upApi"
              :headers="headers"
              :max-count="9"
              :multiple="true"
              :show-upload-list="false"
              class="absolute left-0 top-0 opacity-0"
              name="file"
              @change="handleChange($event, item.id)"
            >
              <Button>上传</Button>
            </Upload>
          </div>
        </div>
      </div>
    </CheckboxGroup>
    <div
      v-if="
        !isEdit &&
        list.length === 0 &&
        !['全部', '房间'].includes(currentTabName)
      "
      class="image-list hover:text-primary-500 hover:border-primary-500 relative my-1.5 mr-3 flex cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-gray-400"
    >
      <MdiAdd class="text-2xl" />
      <span class="text-base">点击上传</span>
      <Upload
        :accept="accept"
        :action="upApi"
        :headers="headers"
        :max-count="9"
        :multiple="true"
        :show-upload-list="false"
        class="absolute left-0 top-0 opacity-0"
        name="file"
        @change="handleChange($event, twoCategoryId)"
      >
        <Button>上传</Button>
      </Upload>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.image-list {
  width: 170px;
  height: 200px;

  &-img {
    height: 170px;
  }

  &-text {
    height: 30px;
  }

  &:hover .image-edit {
    opacity: 1;
  }
}

:deep(.ant-upload) {
  display: block;
  width: 170px;
  height: 200px;
}

:deep(.ant-checkbox) {
  display: inline-block;
}

:deep(.ant-checkbox .ant-checkbox-inner) {
  border-radius: 4px;
}

:deep(.ant-image) {
  width: 170px;
  height: 170px;
}
</style>
